package com.mayikt;

/**
 * @Name Test02
 * @Author 枫火
 * @Date 2022/8/31 21:53
 * @Description wait/notify示例
 **/

class Res2 {

    public String name;
    public String sex;
    public volatile boolean flag = false;

}

class WriteThread2 extends Thread {

    private Res2 res;

    public WriteThread2(Res2 res) {
        this.res = res;
    }

    @Override
    public void run() {
        int count = 0;
        while (true) {
            synchronized (res) {
                if (res.flag) {
                    try {
                        res.wait(); // 线程等待，释放当前锁对象
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if (count == 0) {
                    res.name = "小明";
                    res.sex = "男";
                } else {
                    res.name = "小红";
                    res.sex = "女";
                }
                count = (count + 1) % 2;
                res.flag = true;
                res.notify();
            }
        }
    }
}

class ReadThread2 extends Thread {
    private Res2 res;

    public ReadThread2(Res2 res) {
        this.res = res;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (res) {
                if (!res.flag) {
                    try {
                        res.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("姓名:" + res.name + ",性别:" + res.sex);
                res.flag = false;
                res.notify();
            }
        }
    }
}

public class Test02 {
    public static void main(String[] args) {
        Res2 res = new Res2();
        WriteThread2 writeThread = new WriteThread2(res);
        ReadThread2 readThread = new ReadThread2(res);
        writeThread.start();
        readThread.start();
    }
}
